package com.xuecheng.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.constants.UserConstants;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * 统一token解析
 *
 * @author HuangYuwu
 * @CreateTime 2022/9/11 10:51
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 取出网关提供的payload
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("UTF-8");
         /*String token = request.getHeader("payload");
        AuthInfo authInfo=new AuthInfo();
        if (token != null) {
            authInfo = JwtUtils.getInfoFromToken(token);
        }*/
        // 1.取出payload头
        String payload = request.getHeader("payload");
        AuthInfo authInfo = null;
        if (payload != null) {
            String decode = URLDecoder.decode(payload, "UTF-8");
            // 2.转为java对象
            authInfo = JSON.parseObject(decode, AuthInfo.class);
        }

       /* if (authInfo != null) {
            Map map = (Map) redisTemplate.opsForValue().get(UserConstants.USER_ID + authInfo.getUid());
            System.out.println(map);
            if (map != null) {
                authInfo.setUserName((String) map.get("userName"));
                authInfo.setCompanyName((String) map.get("companyName"));
            }
        }*/
        // 3.存入线程
        AuthInfoHolder.setAuthInfo(authInfo);
        // 4.放行
        return true;
    }

    /**
     * 删除线程绑定
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthInfoHolder.remove();
    }
}
